﻿let async = require("async");
let User = require("./User");
let gameDao = require("./../dao/gameDao");
let redis_dao = require("./../dao/redis_dao");
let arithmetic = require("./arithmetic");
let sever = require("./sever");
let schedule = require("node-schedule");
let gameConfig = require("./../config/gameConfig");
let configDao = require("./../dao/configDao");
let gameAccountDao = require("./../../CClass/dao/gameAccountDao");
let redis_send_and_listen = require("./../../util/redis_send_and_listen");
let log = require("./../../util/loginfo").getInstand;

//读取文件包
var RewardHorseNo = -1;
var RoundNo = 0;

let GameInfo = function () {

    let _gameinfo = "";

    let Game = function () {

        //初始化算法，使用第X种
        this.initAlgorithm = function (idx) {
            log.info('####init Algorithm!####');
            log.info('use [' + idx + '] Algorithm!');
            this.A = new arithmetic(idx);
        };

        this.serverId = gameConfig.serverId;

        //初始化游戏
        this.init = function () {
            log.info('----init game!----');

            //初始化算法
            this.initAlgorithm(0);
            //初始化用户列表
            this.userList = {};
            //在线人数为0
            this.onlinePlayerCount = 0;
            //统计
            this.winTotal = 0;
            this.lotteryCount = 0;
            this.hourWinTotal = 0;
            this.hourlotteryCount = 0;


            //初始化清除数组
            redis_dao.init_bet_list();

            this.bet_user_pool = [0, 0, 0, 0, 0, 0, 0, 0];
            this.game_record = [];
            this.game_odd = [];

            this.score_changeLogList = [];
            this.lotteryLogList = [];
            this.lineOutList = [];
            this.all_user_bet_list = {};
            this.redis_result = [];

            //维护模式
            this.maintain = false;

            this.times_id = 0;     //当前的局号
            this.game_type = 0;    //游戏状态   0 默认   1开始下注  2 开奖   3结束
            this.game_second = 0; //秒数
            this.game_odd = gameConfig.GAME_COMBINATIONS_SAI_MA;

            this.sever = new sever();
            //查日志
            gameDao.selectGameLog((result) => {
                if (result == 0) {
                    this.times_id = 10000001;
                } else {
                    this.times_id = result[0].id + 1;
                }
                log.info("初始局号: " + this.times_id);
            });
            let rule = new schedule.RecurrenceRule();
            let times = [];
            for (let i = 0; i < gameConfig.GAME_COMPETITION_TIME_ONEGAME; i++) {
                times.push(i);
            }
            rule.second = times;
            let self = this;
            schedule.scheduleJob(rule, function () {
                try {
                    if (gameConfig.maintain) {
                        --gameConfig.maintainTime;
                        //log.info(gameConfig.maintainTime);;
                        if (!gameConfig.maintainTime) {
                            self.disconnectAllUser();
                        }
                    }
    
                    if (self.bet_time > 0) {
                        self.bet_time--;
                    }
    
                    if (self.game_second == 0) {    //开始下注
                        log.info("开始下注  清除数组");
                        redis_dao.init_bet_list();
                        self.game_type = 1;
                        self.bet_time = gameConfig.GAME_COMPETITION_TIME_BETCLOSE;
                        self._io.sockets.emit('BetStart', {
                            result: true,
                            type: 1,
                            obj: {
                                game_second: self.game_second,
                                game_type: self.game_type,
                                game_odd: self.game_odd,
                                times_id: self.times_id
                            }
                        });
                    } else if (self.game_second == gameConfig.GAME_COMPETITION_TIME_BETCLOSE) {   //停止下注  接受下注消息
                        self.game_type = 2;
                        self.bet_user_pool = [0, 0, 0, 0, 0, 0, 0, 0];
                        self._io.sockets.emit('BetStop', {
                            result: true,
                            type: 1,
                            obj: {
                                game_second: self.game_second,
                                game_type: self.game_type
                            }
                        });

                        try {
                            configDao.getHorseNo(self.times_id, function(state, rows) {
                                if (state) {
                                    RewardHorseNo = parseInt(rows[0].value);
                                    RoundNo = parseInt(rows[0].key);
                                    log.info("update horse no " + RewardHorseNo + " key " + rows[0].key + " round no " + RoundNo);
                                    return;
                                }
                            });
                        } catch (error) {
                            log.err(error);
                        }
                    } else if (self.game_second == gameConfig.GAME_COMPETITION_TIME_OPENPRICE) {   //开奖
                        self.game_type = 3;
    
                        try {
                            self.open_win();
                        } catch (error) {
                            log.err(error);
                        }
                    }
    
                    if (self.game_second % 2 == 0) {
                        for (var b_u_p in self.bet_user_pool) {
                            self.bet_user_pool[b_u_p] += RandomNumForList([0, 10, 50, 100])
                        }
                        self._io.sockets.emit('BetPool', {
                            result: self.bet_user_pool
                        });
                    }
    
                    self.lotteryLog();
    
                    if (self.game_second == 0) {
                        redis_send_and_listen.send_msg("OnlineUserMsg", {
                            server_id: gameConfig.serverId,
                            online_num: self.onlinePlayerCount
                        });
                    }
                    if (self.game_second != gameConfig.GAME_COMPETITION_TIME_ONEGAME) {
                        self.game_second++;
                    } else {
                        self.game_type = 4;  //状态设置为该局结束
                        self.game_second=0;
	                    gameDao.selectGameLog((result) => {
	                        self.times_id = result[0].id + 1;
	                        log.info("开奖结束循环局号: " + self.times_id);
	                    });
                    }
                } catch (error) {
                    log.err(error);
                }
            });
        };

        this.checkAndGetBetSum = function(bet_dict_list, nBetSum) {
            for (let i in bet_dict_list) {
                let check_bet_dict = this.A.Check_bet_dict(bet_dict_list[i]);
                if (!check_bet_dict) {
                    log.err("redis_dict缺少字段");
                    return {betSum: nBetSum, code: -1};
                }
                nBetSum += bet_dict_list[i].nBet;
                log.info(" bet value " + bet_dict_list[i].nBet);  
            }
            return {betSum: nBetSum, code: 1};
        };

        this.updateUserGold = function (i, userWin) {
            //判断玩家是否在线
            if (this.userList[i]) {
                var youScore = this.userList[i].getScore();
                this.userList[i].winscore(userWin);
                var youNowScore = this.userList[i].getScore();
                log.info("online open win result user " + i + " gold " + userWin + " change_type " + gameConfig.logflag);

                //记录金钱变化量
                var userInfolog = {
                    userid: i,
                    score_before: youScore,
                    score_change: userWin,
                    score_current: youNowScore,
                    change_type: gameConfig.logflag,
                    isOnline: true
                };
                this.score_changeLogList.push(userInfolog);
                
                log.info("score change list user " + i + " score_before " + youScore + " score_current " + youNowScore);
            } else {
                this._Csocket.emit("GameUpdateGold", {
                    signCode: gameConfig.LoginServeSign,
                    sendUserId: i,
                    sendCoin: userWin,
                    diamond: 0,
                    change_type: gameConfig.logflag
                });
                log.info("offline open win result user " + i + " gold " + userWin + " change_type " + gameConfig.logflag);
            }
        };

        this.lottery = function (_userId, _bet_dict_list, callback) {

            log.info("user bet " + _userId + "round_no = " + this.times_id);
            //下注
            let bet_dict_list = _bet_dict_list;
            log.info(bet_dict_list);
            if (!bet_dict_list) {
                log.err("没有下注信息");
                callback(-1);
                return;
            }

            if (this.game_type != 1 && this.game_type != 2) {		//不是下注时间
                log.err("不是下注时间");
                callback(-1);
                return;
            }
            if (!_userId) {					//传输ID错误
                log.err("未传用户ID");
                callback(-1);
                return;
            }
            if (!this.userList[_userId]) {	//未找到用户
                log.err("找不到用户");
                callback(-1);
                return;
            }

            //检查下注字典
            let nBetSum = 0;
            let retStru1 = this.checkAndGetBetSum(bet_dict_list, nBetSum);
            if (retStru1.code == 1) {
                nBetSum = retStru1.betSum;
                log.info("user bet " + _userId + " nBetSum = " + nBetSum);
            } else {
                callback(-1);
                return;
            }

            try {
                log.info("redis result " + this.redis_result);

                //用户扣钱
                let lotteryResult = this.userList[_userId].lottery(nBetSum);
                if (!lotteryResult) {
                    log.err(_userId + "分数不够");
                    callback(-2);
                    return;
                }

                // 金额汇总
                for (let j in bet_dict_list) {
                    if (bet_dict_list[j] == undefined) {
                        continue;
                    }
                    let flag = false;
                    for (let i in this.redis_result) {
                        let betInfoTmp = this.redis_result[i];
                        if (_userId == betInfoTmp["userId"] && bet_dict_list[j].nBetItem == betInfoTmp["nBetItem"]) {
                            betInfoTmp["nBet"] += bet_dict_list[j].nBet;
                            flag = true;
                            log.info("bet area " + betInfoTmp["nBetItem"] + " bet value " + betInfoTmp["nBet"]);
                            break;
                        }
                    }
                    if (!flag) {
                        bet_dict_list[j].userId = _userId;
                        this.redis_result.push(bet_dict_list[j]);
                        log.info("bet area " + bet_dict_list[j].nBetItem + " bet value " + bet_dict_list[j].nBet);
                    }
                }

                let GamblingBalanceLevelBigWin = this.A.getGamblingBalanceLevelBigWin(); //获取库存 水位 大奖幸运值
                //水位
                let nGamblingWaterLevelGold = GamblingBalanceLevelBigWin.nGamblingWaterLevelGold;
    
                let addBalanceGold = parseInt(nBetSum * parseInt(nGamblingWaterLevelGold) / 100);    //进入库存的钱
                let addWinPool = parseInt(nBetSum - addBalanceGold);                     //进入奖池的钱
                //增加库存和奖池
                this.A.addGamblingBalanceGold(addBalanceGold, addWinPool);
    
                this.all_user_bet_list[_userId.toString()] = _userId;
                log.info("lottery bet list == " + this.all_user_bet_list[_userId.toString()]);
                // 统计此玩家的下注
                let this_bet_list = [0, 0, 0, 0, 0, 0, 0, 0]; //# 普通下注数组
                let betInfo_list = this.redis_result;
                let bet_list = [];
                let bet_total = 0;

                for (let i in betInfo_list) {
                    let betInfo = betInfo_list[i];
                    if (parseInt(betInfo["userId"]) == _userId) {
                        let nItem = parseInt(betInfo["nBetItem"]);   //马号
                        this_bet_list[nItem] += betInfo["nBet"];
                    }
                }
                for (let i in this_bet_list) {
                    let nBet = this_bet_list[i];
                    let jBet = {};
                    if (nBet > 0) {
                        bet_total += nBet;
                        jBet[i+""] = nBet;
                        bet_list.push(jBet);
                    }
                }
                //log.info("bet_list = " + JSON.stringify(bet_list) + "bet_total = " + bet_total);
                // 写入数据库
                var CoinLog = [];
                var logTemp = {
                    userId: parseInt(_userId),
                    useCoin: bet_total,
                    winCoin: 0,
                    tax: 0,
                    serverId: gameConfig.serverId,
                    gameId: gameConfig.gameId,
                    round_no: this.times_id,
                    bet_list: JSON.stringify(bet_list),
                    result: ""
                };
                CoinLog.push(logTemp);
                log.info("logTemp = " + JSON.stringify(logTemp));
                this._Csocket.emit("insertMark", CoinLog);

                callback(2);
                return;
            } catch (error) {
                log.err("lottery error " + error);
                callback(-1);
                return;
            }
        };

        this.tt = 0;

        this.open_win = function () {
            log.info("开始开奖");
            if (this.game_type != 3) {
                log.err("game_type不是3 不能开奖:" + this.game_type);
                return;
            }

            //开奖
            //获取下注数据
            let redis_dict = this.redis_result;

            let GamblingBalanceLevelBigWin = this.A.getGamblingBalanceLevelBigWin(); //获取库存 水位 大奖幸运值
            //奖池
            let nGamblingWinPool = GamblingBalanceLevelBigWin.nGamblingWinPool;
            var isCtrlRoundNO = false;
            if (RoundNo == this.times_id) {
                isCtrlRoundNO = true;
            }
            log.info("round no ", RoundNo, " times id ", this.times_id, " is control ", isCtrlRoundNO);
            let dictAnalyseResults = this.A.gameProcessor(this.game_odd, redis_dict, nGamblingWinPool, RewardHorseNo, isCtrlRoundNO, RoundNo);

            let winscore = 0;
            let win_userlist = dictAnalyseResults["win_user_list"]; //赢钱字典
            let bet_userlist = dictAnalyseResults["bet_user_list"];//下注字典

            //给玩家加钱
            for (var i in dictAnalyseResults["win_user_list"]) {
                var user_win = dictAnalyseResults["win_user_list"][i];
                if (!user_win) {
                    continue;
                }

                winscore += user_win;
                this.updateUserGold(i, user_win);
            }

            //减少奖池
            if (winscore > 0) {
                this.A.subGamblingBalanceGold(0, winscore)
            }
            log.info("奖池减少 " + winscore + " 奖池" + GamblingBalanceLevelBigWin.nGamblingWinPool);

            //制作结果
            let result = {
                ResultCode: 1,
                win_card_index: dictAnalyseResults["win_card_index"],
                win_card: dictAnalyseResults["win_card"],
                win_list: dictAnalyseResults["win_list"],
            };
            log.info("开奖结果: ResultCode " + result.ResultCode + " win_card_index " + result.win_card_index + " win_card " + result.win_card + " win_list " + result.win_list);

            //保存游戏历史结果
            this.game_record.push(result);
            if (this.game_record.length > 10) {
                this.game_record.splice(0, 1);
            }
            if (this.game_record.length > 10) {
                while (true) {
                    this.game_record.splice(0, 1);
                    if (this.game_record.length < 11) {
                        break;
                    }
                }
            }

            //推消息
            for (let i in this.userList) {
                let win = 0;
                if (win_userlist[i]) {
                    win = win_userlist[i];
                }
                result["win"] = win;
                result["score"] = this.userList[i].getScore();
                this.userList[i]._socket.emit('OpenWinResult', result);

                if (bet_userlist[i]) {
                    //写入服务器记录
                    //1.写记录
                    let you_now_Score = this.userList[i].getScore();
                    let userInfo = {
                        userid: i,
                        bet: bet_userlist[i],
                        score_before: you_now_Score - win + bet_userlist[i],
                        score_win: win,
                        score_current: you_now_Score,
                        result_array: dictAnalyseResults["win_list"],
                    };
                    this.lotteryLogList.push(userInfo);
                }
            }

            //1.写记录
            var CoinLog = [];
            let betInfoList = dictAnalyseResults["betInfo"];
            for (var i in win_userlist) {
                if (i < 10000) {
                    continue;
                }
                try {
                    let betlist_array = [];
                    for (let j in betInfoList) {
                        let betInfo = betInfoList[j];
                        if (parseInt(betInfo["userId"]) == i) {
                            let info = {};
                            info[betInfo["nBetItem"].toString()] = betInfo["nBet"];
                            betlist_array.push(info);
                        }
                    }

                    var logTemp = {
                        userId: parseInt(i),
                        useCoin: bet_userlist[i],
                        winCoin: win_userlist[i],
                        tax: 0,
                        serverId: gameConfig.serverId,
                        gameId: gameConfig.gameId,
                        round_no: this.times_id,
                        bet_list: JSON.stringify(betlist_array),
                        result: dictAnalyseResults["win_card"]
                    };
                    CoinLog.push(logTemp);
                } catch (error) {
                    log.err("insert mark error = " + error);
                }
            }
            if (CoinLog.length > 0) {
                this._Csocket.emit("insertMark", CoinLog);
            }
            
            //保存奖池
            this.saveGamblingBalanceGold();

            //存日志
            gameDao.saveGameLog(JSON.stringify(dictAnalyseResults));

            for (let u in this.all_user_bet_list) {
                redis_dao.del_bet(u);
            }
            this.all_user_bet_list = {};
            this.redis_result = [];
        };

        this.setIo = function (_io, _Csocket) {
            this.sever.setIo(_io, _Csocket);
            this._io = _io;
            this._Csocket = _Csocket;
        };

        this.Setmaintain = function () {
            gameConfig.maintain = true;
        };

        this.isMaintain = function () {
            return gameConfig.maintain;
        };

        //判断是否是同一scoket连续登录，不允许
        this.isLoginAgain = function (socket) {
            if (socket.userId) {
                return this.userList[socket.userId].Islogin();
            } else {
                return false;
            }
        };

        //添加用户
        this.addUser = function (_userInfo, socket) {
            this.userList[_userInfo.userid] = new User(_userInfo, socket);
        };

        this.updateUser = function (userInfo) {
            log.info("updateUser user " + userInfo._userId);
            if (!this.userList[userInfo._userId]) return;

            //已经断线
            if (this.userList[userInfo._userId]._isLeave) {
                let result = {ResultCode: 0, userId: userInfo._userId};
                this._Csocket.emit("userDisconnect", result);
                delete this.userList[userInfo._userId];
                return;
            }
            this.userList[userInfo._userId].update(userInfo);

            this.LoginGame(userInfo._userId, this.serverId);
            ++this.onlinePlayerCount;

            let resultObj = {
                account: this.userList[userInfo._userId]._account,
                id: this.userList[userInfo._userId]._userId,
                nickname: this.userList[userInfo._userId]._nickname,
                headimgurl: this.userList[userInfo._userId]._headimgurl,
                score: this.userList[userInfo._userId]._score,
                game_second: this.game_second,
                game_type: this.game_type,
                game_odd: this.game_odd,
                times_id: this.times_id,
                time_betClose: gameConfig.GAME_COMPETITION_TIME_BETCLOSE,
                time_openPrice: gameConfig.GAME_COMPETITION_TIME_OPENPRICE,
                time_oneGame: gameConfig.GAME_COMPETITION_TIME_ONEGAME,
            };
            result = {
                resultid: '1',
                msg: 'login lineserver succeed!',
                Obj: resultObj
            };
            this.userList[userInfo._userId]._socket.emit('loginGameResult', result);

        };

        //获得在线人数
        this.getOnlinePlayerCount = function () {
            return this.onlinePlayerCount;
        };

        //在线所有人
        this.getOnlinePlayer = function () {
            return this.userList;
        };

        this.score_changeLog = function () {
            let saveListTemp = [];
            let ItemTemp;
            let max = 0;
            if (this.score_changeLogList.length > 200) {
                max = 200;
            } else {
                max = this.score_changeLogList.length;
            }
            for (var i = 0; i < max; i++) {
                if (this.score_changeLogList.length > 0) {
                    ItemTemp = this.score_changeLogList.shift();
                    saveListTemp.push(ItemTemp);
                }
            }
            if (saveListTemp.length > 0) {
                this._Csocket.emit("score_changeLog", saveListTemp);
                gameDao.score_changeLog(saveListTemp);
            }
        };

        this.lotteryLog = function () {
            let saveListLotteryLogTemp = [];
            let ItemTemp;
            let max = 0;
            if (this.lotteryLogList.length > 200) {
                max = 200;
            } else {
                max = this.lotteryLogList.length;
            }
            for (let i = 0; i < max; i++) {
                if (this.lotteryLogList.length > 0) {
                    ItemTemp = this.lotteryLogList.shift();
                    saveListLotteryLogTemp.push(ItemTemp);
                }
            }
            if (saveListLotteryLogTemp.length > 0) {
                gameDao.lotteryLog(saveListLotteryLogTemp);
            }
        };

        //查询开奖记录
        this.selectRecord = function (socket) {
            gameDao.selectGameLog((result) => {
                socket.emit('getGameRecordResult', {game_record: result});
            });
        };

        //删除用户
        this.deleteUser = function (_socket) {
            if (_socket.userId) {
                this._Csocket.emit("lineOut", {
                    signCode: gameConfig.LoginServeSign,
                    state: 0,
                    gameId: gameConfig.gameId,
                    serverId: gameConfig.serverId,
                    userId: _socket.userId,
                    tableId: -1,
                    seatId: -1
                });
                this.sever.LogoutRoom(this.userList[_socket.userId], _socket);
                delete this.userList[_socket.userId];
                --this.onlinePlayerCount;
            }
        }

        //删除用户
        this.sendLoginGameFailed = function (_userId, msg) {
            if (_userId) {
                var socketItem = this.userList[_userId]._socket;
                result = {resultid: 0, msg: msg};
                socketItem.emit('loginGameResult', result);
                delete this.userList[_userId];
            }
        }

        //获得用户当前分数
        this.getUserscore = function (_userId) {
            if (_userId) {
                return this.userList[_userId]._score;
            }
        }

        //获得用户
        this.getUser = function (_userId) {
            if (_userId) {
                return this.userList[_userId];
            }
        }

        //用户是否在线
        this.IsPlayerOnline = function (_userId) {
            if (!_userId) {	//传输ID错误
                log.err("IsPlayerOnline 查询在线,参数错误!");
                return -1;
            }
            if (this.userList[_userId]) {//未找到用户
                log.err("IsPlayerOnline 查询在线,未找到 " + _userId + " 用户!");
                return 1;
            } else {
                return 0;
            }
        }

        //获得用户当前分数
        this.getPlayerScore = function (_userId) {
            if (!_userId) {	//传输ID错误
                log.err("getPlayerScore 查询分数,参数错误");
                return -1;
            }
            if (this.userList[_userId]) {//未找到用户
                log.err("getPlayerScore 查询在线,未找到" + _userId + "用户");
                return this.userList[_userId].getScore();
            } else {
                return -1;
            }
        }

        //GM加分
        this.addgold = function (_userId, score) {
            if (!_userId) {					//传输ID错误
                log.err("addgold 加分,未登录");
                return 0;
            }
            if (!this.userList[_userId]) {	//未找到用户
                log.err("加分,未登录");
                return 0
            } else {
                log.info(score);
                if (this.userList[_userId].addgold(score)) {
                    log.info(this.userList[_userId].getScore())
                    log.info("加分成功!")
                    var tablestring = "table" + this.userList[_userId].getTable();
                    this._io.sockets.in(tablestring).emit('addgoldResult', {
                        userId: _userId,
                        userSeatId: this.userList[_userId].getSeat(),
                        userScore: this.userList[_userId]._score
                    })
                    return 1;
                } else {
                    log.err("减分失败,大于用户分数!");
                    return 0;
                }
            }
        }

        //保存时间段输赢状况
        this.saveSocrePool = function () {
            //获得虚拟池
            var Virtualpool = this.A.getVirtualScorePool();
            //获得实际池
            var poollist = this.A.getScorePoolList();

            //var poollistLength = this.A.getScorePoolListLength();

            var poollistId = this.A.getScoreId();

            gameDao.Update_score_pool(poollist, Virtualpool, poollistId, function (Result) {
            })
        }

        //保存库存 奖池
        this.saveGamblingBalanceGold = function () {
            //获得库存奖池
            var dict = this.A.getGamblingBalanceGold();

            gameDao.Update_GamblingBalanceGold(dict.nGamblingBalanceGold, dict.nGamblingWinPool, function (Result) {
            })
        }


        //进入游戏
        this.LoginGame = function (_userId, gametype) {
            if (!this.userList[_userId]) return;
            //用户添加游戏ID
            log.info(_userId + " 用户进入游戏 type " + gametype);
            this.userList[_userId].loginGame(gametype);
        }


        //进入房间
        this.LoginRoom = function (_userId, roomid, _socket) {
            if (!this.userList[_userId]) return;

            if (!this.userList[_userId].getGameId()) {
                log.info("用户" + _userId + ",没有进入任何游戏,进入房间")
                return;
            }

            if (this.userList[_userId].getSeat() != -1) {
                log.info("用户" + _userId + "已经有座位");
                return;
            }

            this.userList[_userId].loginRoom(roomid);
            var LoginResult;
            var linemsg = this.getLineOutMsg(_userId);
            if (linemsg.Result) {
                log.info("断线重连接table:" + linemsg.tableId + " seatid:" + linemsg.seatId);
                LoginResult = this.sever.LoginRoombyLineOut(this.getUser(_userId), _socket, linemsg.tableId, linemsg.seatId);
                this.lineOutSet({state: 0, userId: _userId});
            } else {
                LoginResult = this.sever.LoginRoom(this.getUser(_userId), _socket);
            }
            //进入房间后，帮分配座位
            // LoginResult
            //发送场景消息给当前用户
            var tableUserList = Array();

            for (var i = 0; i < this.sever.seatMax; i++) {
                //除了自己以外
                //log.info(LoginResult.tableId);
                //log.info(this.sever.tableList);
                if (this.sever.tableList[LoginResult.tableId][i] && this.sever.tableList[LoginResult.tableId][i] != _userId) {
                    var userItem = {};
                    var userid = this.sever.tableList[LoginResult.tableId][i];

                    if (this.userList[userid]) {
                        //先确定在线才能拿到相关信息
                        userItem.userId = this.userList[userid].getUserId();
                        userItem.seatId = this.userList[userid].getSeat();
                        userItem.nickname = this.userList[userid]._nickname;
                        userItem.score = this.userList[userid]._score;
                        userItem.userType = this.userList[userid]._Robot;
                        var url = 0;
                        if (this.userList[userid]._headimgurl) {
                            url = ""
                        }

                        userItem.headimgurl = url;
                        tableUserList.push(userItem);
                    }
                }
            }
            //发送场景消息
            //检查自己下注情况,效准玩家金额
            var self = this;
            gameDao.getFreeCount(_userId, function (ResultCode, Result) {
                //log.info("**" + Result.Id);
                if (!self.userList[_userId]) return;
                Result.Id = _userId
                self.userList[_userId].updateFreeGame(Result);
                log.info("从数据库里获得免费次数" + Result.freeCount);

                var ResultData = {
                    TableId: LoginResult.tableId,
                    seatId: LoginResult.seatId,
                    userList: tableUserList,
                    freeCount: self.userList[_userId].getFreeCount(),
                    score_pool: self.A.getVirtualScorePool()
                }
                _socket.emit("LoginRoomResult", {ResultCode: 1, ResultData: ResultData});

                if (!linemsg.Result) {
                    var tablestring = "table" + LoginResult.tableId;
                    var url = 0;
                    if (self.userList[_userId]._headimgurl) {
                        url = ""
                    }
                    _socket.broadcast.to(tablestring).emit('playEnter', {
                        ResultCode: 1,
                        ResultData: {
                            userId: _userId,
                            TableId: LoginResult.tableId,
                            seatId: LoginResult.seatId,
                            nickname: self.userList[_userId]._nickname,
                            score: self.userList[_userId]._score,
                            headimgurl: url,
                            userType: self.userList[_userId]._Robot
                        }
                    });
                }

            })

        };

        //断线保存
        this.lineOutSet = function (_info) {
            if (_info.state == 1) {
                //添加
                this.lineOutList[_info.userId] = {tableId: _info.tableId, seatId: _info.seatId}
                //log.info(this.lineOutList[_info.userId]);
            } else {
                //移除
                this._Csocket.emit("lineOut", {
                    signCode: gameConfig.LoginServeSign,
                    state: 0,
                    gameId: gameConfig.gameId,
                    userId: _info.userId
                })
                delete this.lineOutList[_info.userId];
            }
        };

        //获得断线用户信息
        this.getLineOutMsg = function (_userId) {
            if (this.lineOutList[_userId]) {
                this.lineOutList[_userId].Result = 1;
                return this.lineOutList[_userId];
            } else {
                return {Result: 0};
            }
        };

        //清楚断线用户信息
        this.cleanLineOut = function () {
            //清理登录服务器
            log.info(this.lineOutList)
            for (var Item in this.lineOutList) {
                Item = parseInt(Item)
                var tableid = this.lineOutList[Item].tableId;
                var tablestring = "table" + tableid;
                this._io.sockets.in(tablestring).emit('PlayerOut', {
                    PlayerSeatId: this.lineOutList[Item].seatId,
                    userId: Item
                });
                this.sever.cleanLineOut(tableid, this.lineOutList[Item].seatId)
                this._Csocket.emit("lineOut", {
                    signCode: gameConfig.LoginServeSign,
                    state: 0,
                    gameId: gameConfig.gameId,
                    userId: Item
                })
            }
            this.lineOutList = {};
        };

        this.getDownTime = function (_socket) {
            if (!this.userList[_socket.userId]) {
                //log.info("用户" + _socket.userId + "不存在");
                return;
            }

            var tableid = this.userList[_socket.userId].TableId;
            if (tableid < 0) {
                _socket.emit("getDownTimeResult", {ResultCode: 0, msg: "用户没有进入桌子"});
                return;
            }

            if (this.upUserList[tableid].length == 0) {
                _socket.emit("getDownTimeResult", {
                    ResultCode: 1,
                    downTime: this.sever.downTime,
                    upUserList: [],
                    upCoin: 0,
                    DownCoin: [0, 0, 0],
                    myDownCoin: [0, 0, 0]
                });
                return;
            }

            var down1 = 0;
            var down2 = 0;
            var down3 = 0;
            for (var itme in this.downCoinList[tableid]) {
                down1 += this.downCoinList[tableid][itme][0];
                down2 += this.downCoinList[tableid][itme][1];
                down3 += this.downCoinList[tableid][itme][2];
            }

            var mydown1 = 0;
            var mydown2 = 0;
            var mydown3 = 0;
            if (this.downCoinList[tableid][_socket.userId]) {
                mydown1 = this.downCoinList[tableid][_socket.userId][0];
                mydown2 = this.downCoinList[tableid][_socket.userId][1];
                mydown3 = this.downCoinList[tableid][_socket.userId][2];
            }

            //每门下注额度
            _socket.emit("getDownTimeResult", {
                ResultCode: 1,
                downTime: this.sever.downTime,
                upUserList: this.upUserList[tableid],
                upCoin: this.upUserList[tableid][0].upCoin,
                DownCoin: [down1, down2, down3],
                myDownCoin: [mydown1, mydown2, mydown3]
            });
        };


        this.disconnectAllUser = function () {
            for (var itme in this.userList) {
                this.userList[itme]._socket.disconnect();
            }
            log.info("服务器开启维护，已经全部离线");
        };

        //运行初始化
        this.init();

        this.getMark = function (_info, _socket) {
            gameAccountDao.get_Mark(_info, function(state, rows) {
                if (state==1) {
                    _socket.emit('getMarkResult', {
                        Result: 1,
                        msg: "获取历史记录成功!",
                        data: rows 
                    });
                    log.info("record " + rows);
                } else {
                    _socket.emit('getMarkResult', {
                        Result: 0,
                        msg: "获取历史记录失败!"
                    });
                }
            });
        };
    };


    if (_gameinfo) {
        return {getInstand: _gameinfo}
    } else {
        log.info("####create game!####");
        _gameinfo = new Game();
        return {getInstand: _gameinfo}
    }

}();

function RandomNumForList(arr) {
    //从指定数组中选取随机值
    return arr[Math.floor((Math.random() * arr.length))]
}

module.exports = GameInfo;


//监听gm发送来的消息
redis_send_and_listen.client_1.on("message", function (channel, message) {
    log.info("------------------------------server接收到信息了");
    log.info("channel" + channel);
    log.info("message" + message);
    var message = JSON.parse(message);
    if (channel == "EditLabaSet") {
        if (parseInt(message.serverId) == gameConfig.serverId) {
            if (parseInt(message.type) == 1) {    //修改水位
                GameInfo.getInstand.A.nGamblingWaterLevelGold = parseInt(message.swval);
                log.info("修改水位 " + GameInfo.getInstand.A.nGamblingWaterLevelGold)
            }
            if (parseInt(message.type) == 2) {    //修改难度
                GameInfo.getInstand.A.nGamblingBigWinLevel = message.BigWinlevel.split(',').map(Number);  //大奖幸运等级
                GameInfo.getInstand.A.nGamblingBigWinLuck = message.BigWinluck.split(',').map(Number);    //大奖幸运概率
                log.info("修改难度等级" + GameInfo.getInstand.A.nGamblingBigWinLevel)
                log.info("修改难度幸运" + GameInfo.getInstand.A.nGamblingBigWinLuck)
            }
        }
    }
});